package diona.search

import net.liftweb.squerylrecord.KeyedRecord
import org.squeryl.annotations._
import net.liftweb.record.field._
import net.liftweb.record.{MetaRecord, Record}
import net.liftweb.squerylrecord.RecordTypeMode._
import diona.model.PublisherSchema
import diona.model.pages.PageInfo

/**
 * User: anton
 * Date: 14.07.11 22:12
 */
class SearchItem extends Record[SearchItem] with KeyedRecord[Long]
{
  override def meta = SearchItem

  @Column(name = "id")
  override val idField = new LongField(this)

  val pageId = new LongField(this)
  val resultId = new LongField(this)
  val requestId = new LongField(this)
  val taskId = new LongField(this)
}

object SearchItem extends SearchItem with MetaRecord[SearchItem]
{
  private def table = PublisherSchema.searchItems

  @volatile var savePosts: (SearchTask, Seq[PostInfo]) => SearchResult = (task, posts) => {
    inTransaction {
      val pageIds = PageInfo.savePosts(posts)
      val existingPages = from(table)(t =>
        where(t.pageId in pageIds and t.requestId === task.requestId)
        select(t.pageId)
      ).view.map(_.is).toSet

      val newPageIds = pageIds.filterNot(existingPages.contains(_))

      val result = SearchResult.createForTask(task, newPageIds.length)

      val items = newPageIds
        .map(p => {
        val item = SearchItem.createRecord
          .pageId(p)
          .resultId(result.id)
          .requestId(task.requestId.is)
          .taskId(task.id)
        item
      })

      table.insert(items)
      result
    }
  }
}